package com.jt;

/**
 * @author 金帮嘉诚 @date 2021-09-06 星期一 15:50
 */

import redis.clients.jedis.Jedis;

import java.util.Random;
import java.util.Scanner;

/**
 * 生成验证码流程demo
 */
public class CodeDemo01 {
    static String host = "192.168.126.128";

    private static void doLogin(String username, String password, String code) {
        //1.校验验证码
        if (code == null) {
            System.out.println("Please input code");
            return;
        }

        Jedis jedis = new Jedis(host, 6379);
        String dbCode = jedis.get("code");//变量名可以根据ip地址

        if (dbCode == null) {
            System.out.println("code timeout");
            return;
        }
        if (!code.equalsIgnoreCase(dbCode)) {
            System.out.println("input error");
            return;
        }
        System.out.println("验证码输入正确...");

        System.out.println("验证用户身份....");

    }

    public static void main(String[] args) {
        //给出一个随机验证码
//        String code = "123A";
        String code = randomCode();

        Jedis jedis = new Jedis(host, 6379);
        jedis.set("code", code);
        jedis.expire("code", 60);
        jedis.close();

        System.out.println(code);

        System.out.println("请输入验证码:..");

        String nextLine = new Scanner(System.in).nextLine();
        doLogin("kim", "123", code);

    }

    // 随机验证码
    static String randomCode() {
        char[] chars = {
                'A', 'B', 'C', 'D', 'E', 'F', 'G',
                'H', 'I', 'J', 'K', 'L', 'M', 'N',
                'O', 'P', 'Q',
                'R', 'S', 'T',
                'U', 'V', 'W',
                'X', 'Y', 'Z',
                '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'
        };

        StringBuilder code = new StringBuilder("");

        for (int i = 0; i < 4; i++) {
            code.append(chars[new Random().nextInt(chars.length - 1)]);
        }
        return code.toString();
    }


}
